<script>
export default {
  name: "CatMedicalRecord"

}
</script>
<script setup>
import mitt from '@/views/lending/utils/mitt';
import lendingRegisterApi from "@/views/lending/Api/lendingRegisterApi";
import BorrowingAuditApi from "@/views/lending/Api/BorrowingAuditApi";

import BorrowingReturnApi from "@/views/lending/Api/BorrowingReturnApi";
import {inject, onMounted, onUnmounted, ref, watch,} from "vue";
import {ArrowLeft, FirstAidKit, User} from "@element-plus/icons-vue";
import CryptoJS from "crypto-js"
import {useRoute} from "vue-router";
import router from "@/router";
import {right} from "core-js/internals/array-reduce";
import {ElMessage, ElMessageBox} from "element-plus";
//id:id信息
const id = ref('');
//rejectReason：驳回理由
const rejectReason = ref('')
//targetName:调用组件名
const targetName= ref('');
//patientInfo:患者信息
const patientInfo = ref('');
//borrowInfo:借阅信息
const borrowInfo = ref('')
//specificFunctions:定制功能
const specificFunctions = ref('')
//specificColor:定制颜色
const specificColor = ref('')
//title:标题
const title = ref('')
//routerGoTo:跳转的目标路由
const routerGoTo = ref('')
//fieldMap:字段映射
const fieldMap =ref('')
//  解密数据
const secretKey = ref(''); // 必须与加密时使用的密钥相同
//ruleControlData:接收数据.
//  ruleControlData:获取路径中的id
const ruleControlData = ref('');
//recordStatusValue:病案状态转换规则
const recordStatusValue = ref()
//info:存储id查询回来的记录
const info = ref({})
//rightShow
const rightShow = ref()
//getRuleData:接收处理数据
function getRuleData(){


  // 解密
  const route = useRoute();
  //获取id
  id.value = route.query.id
  const encryptedData = route.query.temp;

  //获取秘钥
  if(secretKey.value === ''){
    getSession()
  }
  //获取数据
  ruleControlData.value = JSON.parse(CryptoJS.AES.decrypt(encryptedData,secretKey.value).toString(CryptoJS.enc.Utf8));

}
//getSession:获取秘钥
function getSession(){
  if(!sessionStorage.getItem('catSecretKey')){
    alert('数据未同步,请退回列表，重新进入')
  }
  //获取秘钥
  secretKey.value = sessionStorage.getItem('catSecretKey');

}
//initialize：初始化数据
const initialize = () => {
  ruleControlData.value.forEach((ruleItem) => {
    Object.keys(ruleItem).forEach((keyItem) => {
      switch (keyItem){
        case 'targetName':
          targetName.value = ruleItem[keyItem]
          break
        case 'patientInfo':
          patientInfo.value = ruleItem[keyItem]
          break
        case 'borrowInfo':
          borrowInfo.value = ruleItem[keyItem]
          break
        case 'specificColor':
          specificColor.value = ruleItem[keyItem]
          break
        case 'specificFunctions':
          specificFunctions.value = ruleItem[keyItem]
          break
        case 'title':
          title.value = ruleItem[keyItem]
         break
        case 'routerGoTo':
          routerGoTo.value = ruleItem[keyItem]
          break
        case 'fieldMap':
          fieldMap.value = ruleItem[keyItem]
          break
        case 'recordStatusValue':
          recordStatusValue.value = ruleItem[keyItem]
          break
        case 'rightShow':
          rightShow.value = ruleItem[keyItem]
          break
        default:
          console.warn(`Unknown key: ${keyItem}`);
          break;
      }
    });
  });

};

//colorControl:颜色控制
const colorControl =  (name) => {
  for (const key in specificColor.value){
    if (specificColor.value[key].hasOwnProperty(name)){
      return specificColor.value[key][name]
    }
  }
  return 'color:#7F7F7F'
}
//routerControl:路由控制
const routerControl = (name) => {

  for (const key in routerGoTo.value){
    if (routerGoTo.value[key].hasOwnProperty(name)){
      router.push(routerGoTo.value[key][name])
      return;
    }
  }
  router.go(0)
}


//recordStatusComputed:病案状态转换
const recordStatusComputed = ()=>{
  let name = ref('')
  //获取当前组件对应病案状态的字段名
  fieldMap.value.forEach((item)=>{
    if (item['病案状态'] ){
      name.value = item['病案状态']
    }
  })
  for (const key in info.value) {
    let temp = String(info.value[name.value])
    recordStatusValue.value.forEach((dataItem)=>{
      for (const key in dataItem){
        if(temp === key){
          temp = dataItem[key]
          return
        }
      }
    })
    info.value[name.value] = temp
  }
}
//getFieldInfoShow：获取字段值
const getFieldInfoShow =(value)=>{
  const temp = ref()
  for (let i = 0; i < fieldMap.value.length; i++){
    if (fieldMap.value[i][value] !== undefined){
      temp.value = fieldMap.value[i][value]
    }
  }
  for (const key in info.value) {
    if (temp.value === key){
      return info.value[temp.value]
    }
  }
}
//判断组件出处,并且初始化表单
const fromComponent = (componentName)=>{
  if(targetName.value === 'LendingRegisterView'){
    catFormDataGetRegister()
  }
  if(targetName.value === 'BorrowingAuditView'){
    catFormDataGetAudit()
  }
  if (targetName.value === 'BorrowingReturnView'){
    catFormDataGetReturn()
  }

};
//isRightShow:根据病案状态判断展示具体
const  isRightShow = (value)=> {

  for (let i = 0; i < rightShow.value.length; i++){
    if (rightShow.value[i][getFieldInfoShow('病案状态')]){

      if (rightShow.value[i][getFieldInfoShow('病案状态')].includes(value) === true){
        return true
      }

    }
  }
  return false
}
//rightTrigger:点击触发具体功能
const rightTrigger = (item) =>{
  console.log(item)
  switch (item){
    case '审核通过':
      toExaminePass()
      break;
    case '审核驳回':
      rejectReasonOpen()
      break;
    case '取消登记':
      console.log('取消登记')
      cancelRegisterOpen()
      // toCancelRegister()
      break;

    default:
      alert('未匹配到功能')
  }
}
//rejectReasonOpen:驳回理由的出发的弹框
const rejectReasonOpen = () => {
  ElMessageBox.prompt('请输入驳回借阅登记理由！', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputPattern:
        /^(?!\\s*$).+$/,
    inputErrorMessage: '输入不能为空！',
  })
      .then(({value}) => {
        ElMessage({
          type: 'success',
          message: `操作成功`,
        })
        rejectReason.value = value
        toExamineReject()
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '操作取消',
        })
      })
}
//CancelRegisterOpen:取消登记弹窗触发
const cancelRegisterOpen = () => {
  ElMessageBox.confirm(
      '请您确认是否取消登记？确认之后将不再进行受理',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        ElMessage({
          type: 'success',
          message: '操作成功',
        })
        toCancelRegister()
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '操作取消',
        })
        if (targetName.value === 'LendingRegisterView'){
          console.log('嘿嘿嘿');
        }else {
          toCancelRegister()
        }
      })
}

//axios
//-----------------------登记--------------------------------
//catFormDataGetRegister:根据id查询借阅信息
const catFormDataGetRegister = ()=>{
  lendingRegisterApi.selectOne(id.value).then(
      (response)=>{
        info.value = response.data.data
        recordStatusComputed()
      },
      (err)=>{
        console.log(err.message)}
  )
}
//-----------------------审核--------------------------------
//catFormDataGetAudit：根据id查询审核信息
const catFormDataGetAudit = ()=>{
  BorrowingAuditApi.selectOne(id.value).then(
      (response)=>{
        info.value=response.data.data
        recordStatusComputed()
      },
      (err)=>{
        console.log(err.message)}
  )
}
//toExaminePass:审核通过
const toExaminePass = ()=>{
  BorrowingAuditApi.updateStatusPass(id.value).then(
      (response)=>{
        ElMessage.success('操作成功')
        router.push('/lending/borrowingAudit/home')
      },
      (err)=>{
        console.log(err.message)}
  )
}
//toExamineReject:审核驳回
const toExamineReject = ()=>{
  BorrowingAuditApi.updateStatusReject(id.value,rejectReason.value).then(
      (response)=>{
        ElMessage.success('操作成功')
        router.push('/lending/borrowingAudit/home')
      },
      (err)=>{
        console.log(err.message)}
  )
}
//toCancelRegister:取消登记
const toCancelRegister = ()=>{
  BorrowingAuditApi.updateStatusCancel(id.value).then(
      (response)=>{
        console.log(response.data)
        ElMessage.success('操作成功')
        router.push('/lending/borrowingAudit/home')
      },
      (err)=>{
        console.log(err.message)}
  )
}

//-----------------------归还--------------------------------
//catFormDataGetReturn：根据id查询归还信息
const catFormDataGetReturn = ()=>{

  BorrowingReturnApi.selectOne(id.value).then(
      (response)=>{
        info.value=response.data.data
        recordStatusComputed()
      },
      (err)=>{
        console.log(err.message)}
  )
}

//生命周期
//初始化渲染
onMounted(() => {
  //getRuleData：获取查询参数中的加密数据
  getRuleData()
  //initialize：静态字段初始化
  initialize()
  //fromComponent：初始化获取查看信息
  fromComponent()


});

//卸载前
onUnmounted(() => {
  //删除秘钥
  // sessionStorage.removeItem('catSecretKey');
})
</script>
<template>
  <div @click="routerControl('返回')"
      style="  display: flex;
                align-items: center;
                justify-content: flex-end;
                font-size: 14px;
                color: #7F7F7F;
                margin-bottom: 20px;
                margin-right: 77px">
       <el-icon><ArrowLeft /></el-icon>
      <span >返回</span>
  </div>
  <div style="background-color:#F0F2F5;padding: 0;width: 100%;height: 100%;">

      <el-card shadow="never" style="background-color:#fff;padding:5px 0;width: 1150px;margin: 0 auto 20px auto;">

        <div>
          <span class='form-header-one'  >{{title}}</span>
          <span class="form-header-two">
            借阅状态:
            <span :style="colorControl(getFieldInfoShow('病案状态'))"  style="font-size: 20px">{{getFieldInfoShow('病案状态')}}</span>
          </span>
        </div>


<!--        分割线-->
        <el-divider style="margin-top:35px;margin-bottom:10px" content-position="left"/>
<!--    患者信息-->
        <span class="form-header">
          <el-icon style="margin-right: 10px; font-size: 20px;color:#0468FF" ><FirstAidKit /></el-icon>
          患者信息
        </span>
        <el-descriptions :column="4"   style="  margin-top:20px;padding: 0 20px" >
          <el-descriptions-item
              v-for="(item,index) in patientInfo"
              :label="`${item}:` "
              label-align="left"
              align="left"
              width="200px"
              class-name="my-content"
              label-class-name="my-label"
              :key="index"
          >
            <span style="caret-color: #2c3e50"></span>
<!--            <span style="caret-color: #2c3e50">{{getFieldInfoShow(item)}}</span>-->
          </el-descriptions-item>
        </el-descriptions>

<!--    借阅信息-->
        <span class="form-header" style="margin-top: 20px">
          <el-icon style="margin-right: 10px; font-size: 20px;color:#0468FF" ><User /></el-icon>
          借阅信息
        </span>
        <el-descriptions :column="4"  :border="false"  style="  margin-top:20px;padding: 0 20px"  >
          <el-descriptions-item
              :label="`${item}:`"
              label-align="left"
              align="left"
              width="200px"
              class-name="my-content"
              label-class-name="my-label"
              v-for="(item,index) in borrowInfo"
              :key="index"
          >
            <span style="caret-color: #2c3e50">{{getFieldInfoShow(item)}}</span>
          </el-descriptions-item>
        </el-descriptions>
<!--    功能区-->
        <div style="display: inline; justify-content:left;gap: 26px; margin: 20px" v-for="(item,index) in specificFunctions">
          <span>
          <el-button @click="rightTrigger(item)" style="float: left;margin-right: 20px;margin-left: 12px "  v-if="isRightShow(item)" :style="colorControl(item)"  >{{ item }}</el-button>
          </span>
        </div>
      </el-card>
  </div>
</template>

<style scoped>

/* 定义容器的样式 */

.form-header-one{
  float: left;
  font-weight: bold;
  font-size: 20px;
  padding: 0 10px;
}
.form-header-two{
  float: right;
  font-size: 14px;
  color: #7F7F7F;
}
/*.form-header-one{
  display: flex;
  align-items: flex-start;
  justify-content:flex-start;
  height: 40px;
  font-weight: bold; !* 加粗字体 *!
  margin-top:3px;
  padding: 0 10px;
  font-size: 20px;
}*/
.form-header {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  height: 40px;
  font-weight: bold; /* 加粗字体 */
  padding: 0 10px;
  margin-right:1px;
  font-size: 16px;
  color: #000000;
  margin-top: 10px
}
.custom-input   {
  position: absolute;
  left: 0px;
  top: 0px;
  width: 230px;
  height: 32px;
  padding: 2px 10px 2px 10px;
  font-family: 'Microsoft YaHei UI', sans-serif;
  font-weight: 400;
  font-style: normal;
  font-size: 13px;
  letter-spacing: normal;
  color: #000000;
  text-align: left;
  text-transform: none;
  background-color: transparent;
  border-color: transparent;
}
.custom-input-one   {
  position: absolute;
  left: 0px;
  top: 0px;
  height: 32px;
  padding: 2px 10px 2px 10px;
  font-family: 'Microsoft YaHei UI', sans-serif;
  font-weight: 400;
  font-style: normal;
  font-size: 13px;
  letter-spacing: normal;
  color: #000000;
  text-align: left;
  text-transform: none;
  background-color: transparent;
  border-color: transparent;
}
.custom-form-item  {
  --el-form-label-font-size: 13.5px;
}
/*啊实打实*/
:deep(.my-label) {
  color: #000000 !important;
  font-weight: normal !important;
  font-size: 14px !important;
}



 :deep(.my-content) {
   text-align: left !important;
   color: #7F7F7F !important;
   font-size: 14px !important;
 }



</style>
